﻿using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using CH.FourBoards.LagerWalti.Persistence.Entities;

namespace CH.FourBoards.LagerWalti.Persistence.DataAccess.EntityProviders
{
    internal abstract class EntityProvider<T> : IEntityProvider where T : class, IEntity
    {
        protected readonly DataContext Context;

        protected EntityProvider(DataContext context)
        {
            Context = context;
        }

        protected abstract DbSet<T> Set { get; }
        protected abstract IQueryable<T> SetEagerlyLoaded { get; }

        public IEntity Select(int id)
        {
            return Set.FirstOrDefault(e => e.Id == id);
        }

        public IEnumerable<IEntity> SelectAll(bool eagerlyLoading = false)
        {
            return eagerlyLoading ? SetEagerlyLoaded.ToList() : Set.ToList();
        }

        public IEntity Insert(IEntity entity)
        {
            var ret = Set.Add((T) entity);
            Context.SaveChanges();
            return ret;
        }

        public void Update(IEntity entity)
        {
            Context.SaveChanges();
        }

        public void Delete(IEntity entity)
        {
            Set.Remove((T) entity);
            Context.SaveChanges();
        }
    }
}
